#include "componentTable.h"
#include <QMouseEvent>

ComponentTable::ComponentTable(QWidget *parent)
  : QTableWidget(parent)
{
  setDragDropMode(QTableWidget::DropOnly);
  setDefaultDropAction(Qt::CopyAction);
  setAlternatingRowColors(true);
  setSelectionMode(QAbstractItemView::SingleSelection);
  setSelectionBehavior(QAbstractItemView::SelectRows);
}

void ComponentTable::addComponents(const ComponentMap &components, const GraphicsMap& graphics)
{
  unsigned int row(0);
  foreach(Component c, components)
  {
    insertRow(row);
    for(int col(0); col < columnCount(); ++col)
    {
      setItem(row, col, new QTableWidgetItem());
    }

    if (graphics.contains(c.name))
    {
      setItem(row, 0, new QTableWidgetItem(QIcon(graphics[c.name].filename), c.name));
      mGraphics[c.name] = graphics[c.name];
    }
    setItem(row, 1, new QTableWidgetItem(QString::number(c.cells)));
    setItem(row, 2, new QTableWidgetItem(QString::number(c.fuelCost)));
    setItem(row, 3, new QTableWidgetItem(QString::number(c.price)));
    setItem(row, 4, new QTableWidgetItem(c.description));
    mComponents[c.name] = c;
    ++row;
  }
}

Component ComponentTable::component(unsigned int row) const
{
  Component ret;
  if (static_cast<int>(row) < rowCount())
  {
    ret = component(item(row, 0)->text());
  }
  return ret;
}

Component ComponentTable::component(const QString &componentName) const
{
  return mComponents[componentName];
}

QPixmap ComponentTable::pixmap(const QString &componentName) const
{
  QPixmap ret;
  if (mGraphics.contains(componentName))
  {
    ret = mGraphics[componentName].pixmap;
  }
  return ret;
}

void ComponentTable::mousePressEvent(QMouseEvent *event)
{
  if (event->button() == Qt::LeftButton)
  {
    QTableWidgetItem* t(itemAt(QPoint(event->x(), event->y())));
    if (t)
    {
      setCurrentItem(t);
      int r(row(t));
      QTableWidgetItem* key(item(r, 0));
      QDrag *drag(new QDrag(this));
      QMimeData* mimeData(new QMimeData);
      mimeData->setText(key->text());
      drag->setMimeData(mimeData);
      drag->setPixmap(key->icon().pixmap(20, 20));
      drag->setHotSpot(QPoint(drag->pixmap().width()/2, drag->pixmap().height()/2));
      mimeData->setImageData(drag->pixmap());
      Qt::DropAction dropAction(drag->exec(Qt::CopyAction));
      Q_UNUSED(dropAction);
    }
  }
}
